<template>
  <div class="content-box">
    <div ref="searchBox" class="search-box flex" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="100px"
      >
      <el-form-item label="公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          clearable
          filterable
          placeholder="请选择"
          style="width: 240px; margin-right: 20px"
        >
          <el-option
            v-for="(item, index) in companyIdOptionList"
            :key="index"
            :label="item.companyName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="登录账号" prop="account">
          <el-input
            style="width: 240px; margin-right: 20px"
            v-model="queryParams.account"
            placeholder="请输入"
            clearable
          ></el-input>
      </el-form-item>
      <el-form-item label="代号" prop="markName">
          <el-input
            style="width: 240px; margin-right: 20px"
            v-model="queryParams.markName"
            placeholder="请输入"
            clearable
          ></el-input>
      </el-form-item>

      <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            plain
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >
            重置
          </el-button>
          <el-button
             type="primary"
             size="mini"
             @click="handelDialog('添加', null)"
             >添加账号</el-button
           >
        </el-form-item>
      </el-form>
    </div>

    <div class="table-box">
      <el-row :gutter="10" class="mb8">
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="handleQuery"
          :columns="columnsList"
        ></right-toolbar>
      </el-row>
      <el-table
        v-sticky-header
        ref="table"
        v-loading="loading"
        :data="dataList"
        :span-method="objectSpanMethod"
        border
      >
        <template v-for="(item,index) in columns.slice(0, columns.length - 1)">
          <el-table-column
            :key="index"
            :label="item.label"
            :prop="item.prop"
            :width="getColumnWidth(index)"
            :fixed="item.fixed"
            :sortable="item.sortable ? item.sortable : false"
            :show-overflow-tooltip="item.showTooltip"
            v-if="item.visible"
            align="center"
          >
             <template slot-scope="scope">
                <!-- 接单状态单独处理 -->
                <div v-if="item.prop == 'orderStatus'">
                    <el-popconfirm
                      :title="`确定重新${
                        scope.row[item.prop]!== '1' ? '接单' : '不接单'
                      }吗？`"
                      @confirm="changeorderStatus(scope.row)"
                      v-if="scope.row['roleType'] !== 0"
                    >
                      <el-button
                        slot="reference"
                        size="mini"
                        :style="{
                          color:'#fff',
                          backgroundColor: scope.row[item.prop] === '1' ?'#fa8c16':'#5AA4AE',
                          borderColor: scope.row[item.prop] === '1' ?'#fa8c16':'#5AA4AE',
                        }"
                        >{{ scope.row[item.prop] === '1' ? "接单" : "不接单" }}</el-button
                      >
                    </el-popconfirm>
                </div>
                <!-- 账号类型单独处理 -->
                <div v-else-if="item.prop == 'roleType'">
                    <el-tag 
                     :type="roleTypeColor(scope.row[item.prop])" 
                     >
                     {{ ArrayFormatObj(roleTypeOptions)[scope.row[item.prop]]}}
                    </el-tag>
                </div>
                 <!--账号状态单独处理 -->
                <div v-else-if="item.prop === 'status'" @click="showOrOffPopo(scope.row)">
                  <el-popover
                    placement="top"
                    trigger="click"
                    :value ="rowIndex === scope.row.id"
                    title="账号状态操作"
                    v-if="scope.row['roleType'] !== 0"
                    >
                    <el-form >
                      <el-form-item style="margin-bottom: 0;">
                        <el-radio-group v-removeAriaHidden v-model="statesUpd" >
                          <el-radio 
                           v-for="(item,index) in statusOptions" 
                          :key="index" :label="item.value">{{ item.label }}
                        </el-radio>
                       </el-radio-group>
                      </el-form-item>
                      <el-form-item style="display: flex;justify-content: center;margin-bottom: 8px;">
                        <el-button type="primary" @click="clickSubmitOnOrOff(scope.row)">提交</el-button>
                        <el-button @click="clickCancelOnOrOff(scope.row)">取消</el-button>
                      </el-form-item>
                    </el-form>
                    <el-button 
                       slot="reference"
                       :type="statusColor(scope.row[item.prop])" 
                       size="mini" 
                     >{{ ArrayFormatObj(statusOptions)[scope.row[item.prop]]}}</el-button>
                  </el-popover> 
                </div>
                <span v-else>
                  {{  scope.row[item.prop] == null ? '-': scope.row[item.prop] }}
                </span>
             </template>
          </el-table-column>
        </template>
        <el-table-column
            fixed="right"
            :prop="columns[columns.length - 1].prop"
            :label="columns[columns.length - 1].label"
            align="center"
            :width="getColumnWidth(columns.length - 1)"
            v-if="columns[columns.length - 1].visible"
          >
            <template slot-scope="scope">
             <div :class="['flex-center',device === 'mobile'?'flex':'']">
              <el-button
                type="text"
                @click="handelDialog('编辑', scope.row)"
                >编辑</el-button
              >
              <el-popconfirm
                title="确定要删除该账号吗？"
                style="margin-left: 10px"
                @cancel="hanCancelDel"
                @confirm="handelDel(scope.row)"
                v-if="scope.row['roleType'] !== 0"
              >
                <el-button
                  slot="reference"
                  type="text"
                  ><span style="color: #ff116e">删除</span></el-button
                >
              </el-popconfirm>
              <el-button
                type="text"
                style="margin-left: 10px"
                @click="handelDialog('密码重置', scope.row)"
                v-if="scope.row['roleType'] !== 0"
                >密码重置</el-button
              >
             </div>
            </template>
        </el-table-column>
      </el-table>
      <!-- 使用分页插件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[10, 50, 100, 200, 500]"
        :page.sync="queryParams.pageIndex"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 新增/编辑 对话框 -->
      <el-dialog
        :title="title"
        width="650px"
        :visible.sync="dialogShow"
        :before-close="handleClose"
      >
        <el-form :model="form" :rules="rules" label-width="80px" ref="formRef">
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model="form.userName"
              style="width: 100%"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
          <el-form-item label="登录账号" prop="account">
            <el-input
              v-model="form.account"
              style="width: 100%"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
          <el-form-item label="代号" prop="markName">
            <el-input
              v-model="form.markName"
              style="width: 100%"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
          
          <el-form-item
           v-if="isAdd"
           label="公司" prop="companyId" >
              <el-select
               v-model="form.companyId"
               clearable
               filterable
               placeholder="请选择"
               style="width: 100%"
               :disabled="!isAdd"
               @change="companyIdsChange"
              >
                <el-option
                 v-for="(item, index) in companyIdOptionList"
                 :key="index"
                 :label="item.companyName"
                 :value="item.id"
                 ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
             v-else
             label="公司名称" prop="companyName">
            <el-input
              v-model="form.companyName"
              style="width: 100%"
              placeholder="请输入"
              clearable
              :disabled="!isAdd"
            />
          </el-form-item>
            <el-form-item label="接单状态" prop="orderStatus">
               <el-select
                 v-model="form.orderStatus"
                 clearable
                 filterable
                 placeholder="请选择"
                 style="width: 100%"
               >
                 <el-option
                   v-for="(item, index) in orderStatusOptions"
                   :key="index"
                   :label="item.label"
                   :value="item.value"
                 ></el-option>
               </el-select>
           </el-form-item>
        <el-form-item 
           label="管理产品"
           prop="productIds"
           v-show="isAdd || (!isAdd && rowObj.roleType !== 0)"
        >
           <el-select
            v-model="form.productIds"
            multiple
            collapse-tags
            clearable
            filterable
            placeholder="请选择"
            style="width: 100%"
           >
             <el-option
              v-for="(item, index) in productIdsOption"
              :key="index"
              :label="item.productName"
              :value="item.id"
              ></el-option>
           </el-select>
        </el-form-item>
         <el-form-item label="账号类型" prop="roleType">
            <el-select
              v-model="form.roleType"
              clearable
              filterable
              placeholder="请选择"
              style="width: 100%"
              :disabled="(!isAdd && rowObj.roleType === 0)"
            >
              <el-option
                v-for="(item, index) in ((isAdd || rowObj.roleType !== 0)?roleTypeOptions.filter(item=>item.label !== '超管' ):roleTypeOptions)"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item 
          label="上级领导" 
          prop="leaderId"
          v-if="form.roleType == 2"
          >
            <el-select
              v-model="form.leaderId"
              clearable
              filterable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in leaderIdOptions"
                :key="index"
                :label="item.leaderName"
                :value="item.id   "
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="账号状态" prop="status">
            <el-select
              v-model="form.status"
              clearable
              filterable
              placeholder="请选择"
              style="width: 100%"
              :disabled="!isAdd"
            >
              <el-option
                v-for="(item, index) in statusOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleSubmit('formRef')"
            >确 定</el-button
          >
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import tableStickyMixins from "@/mixins/tableStickyMixins";
import { mapGetters } from "vuex";
import {
  queryCrmAccountByPage,
  addOrEditCrmAccount,
  delAccount,
  resetPassword,
  setAccountOrder,
  setAccountStatus,
   queryCrmLeaderList,

} from "@/api/sysCrm/crmAccount";
import {
  queryCrmCompanyList,
  queryCrmProductList
} from "@/api/sysCrm/crmCompany";
export default {
  // 定义名字用于标识该组件是否被keep-alive缓存
  name: "CrmAccount",
  data() {
    return {
      // 数据列表
      dataList: [],
      // 公司集合筛选项
      companyIdOptionList: [],
      // 产品列表筛选项
      productIdsOption:[],

      // 接单状态筛选项
      orderStatusOptions: [
        { label: "不接单", value: '0' },
        { label: "接单", value: '1' },
      ],
      // 账号类型筛选项
      roleTypeOptions: [
        { label: "超管", value: 0 },
        { label: "管理员", value: 1 },
        { label: "接线员", value: 2 },
      ],
      // 领导筛选项(接线员才有领导)
      leaderIdOptions:[],
      // 账号状态筛选项
      statusOptions: [
        { label: "启动", value: 0 },
        { label: "停用", value: 1 },
        { label: "暂停", value: 2 },
      ],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
      },
      loading: false,
      // 表格列信息（用于控制显示与隐藏)
      columnsList:[],
      // 显示搜索栏
      showSearch: true,


      // 显示搜索栏
      showSearch: true,
      // 弹框标题
      title: "",
      // 弹框显示状态
      dialogShow: false,
      // 弹框的表单信息
      form: {},
      // 弹框表单校验规则
      rules: {
          // userName:[
          // { required: true, message: "请填写姓名", trigger: "blur" },
          // ],
          account:[
            { required: true, message: "请填写登录账号", trigger: "blur" },
          ],
          companyId:[
            { required: true, message: "请选择公司", trigger: "change" },
          ],
          roleType:[
            { required: true, message: "请选择账号类型", trigger: "change" },
          ]
      },
      // 回显对象
      rowObj:{},


      // 状态操作当前激活项行数据
      rowIndex:null,
      // 状态修改值
      statesUpd:null,
    };
  },
  mixins: [tableStickyMixins],
  watch: {
    columns: {
      handler() {
        // 清空popover激活项索引
        this.rowIndex = null;
        this.updateTableHeight();
      },
      deep: true,
    },
     dataList:{
      handler() {
        // 清空popover激活项索引
        this.rowIndex = null;
      },
      deep: true,
    },
  },
  created() {
    this.getCompanyIdList();
  },
  computed: {
    ...mapGetters(["sidebar", "device"]),
    // 对状态进行处理
    statusColor:()=>{
        return (state)=>{
           switch(state){
             case 0:
                return 'success';
             case 1:
                return 'info';
             case 2:
                return 'danger';
             default:
           }
        }
     },
    // 计算当前列元素在所处环境的宽度
    getColumnWidth() {
      return (index) => {
        return this.isMobile
          ? this.columns[index].mobileWidth
          : this.columns[index].pcWidth ;
      };
    },
    // 将数组转换为对象形式
    ArrayFormatObj:()=>{
       return (arr)=>{
         return arr.reduce((pre, cur)=>{
           pre[cur.value] = cur.label;
           return pre;
         },{})
       }
    },
    // 账号类型标签颜色处理
    roleTypeColor:()=>{
        return (state)=>{
           switch(state){
             case '0':
                return 'success';
             case '1':
                return 'warning';
             case '2':
                return 'primary';
             default:
           }
        }
    },
    // 表格列信息
    columns(){
      const arr = [
       {label: `公司简称`,prop: "companyName",visible: true,pcWidth: null,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `公司编码`,prop: "companyCode",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `登录账号`,prop: "account",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `代号`,prop: "markName",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `领导`,prop: "leaderName",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `接单状态`,prop: "orderStatus",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       
       {label: `账号类型`,prop: "roleType",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `账号状态`,prop: "status",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `当前管理产品`,prop: "child_productName",visible: true,pcWidth: null,mobileWidth: 120,fixed: null,showTooltip: true,},
       
       {label: `操作`,prop: "operation",visible: true,pcWidth: 150,mobileWidth: 80,fixed: "right",showTooltip: true},
      ]
      this.$set(this,'columnsList',arr)
      return arr
    },
    // 是否新增操作
    isAdd() {
      return this.title === "添加账号";
    },
  },
  methods: {
    // 获取领导列表
    getLeaderList(){
      queryCrmLeaderList({
        id:this.form.id || null,
        companyId:this.form.companyId
      }).then(res => {
        if(res.code == 200){
          this.leaderIdOptions = res.data
        }
      })
    },
    // 公司筛选条件改变
    companyIdsChange(){
       this.getProductList()
       this.getLeaderList()
    },
    // 获取公司筛选项列表
    getCompanyIdList(){
      queryCrmCompanyList().then(res=>{
        this.companyIdOptionList = res.data
      })
    },
    // 获取产品筛选项列表
    getProductList(){
      // 获取下游产品列表
      queryCrmProductList({
         companyIds:this?.form?.companyId == null ? null : [this?.form?.companyId]
      }).then((res) => {
         this.productIdsOption = res.data;
      });
    },
    // 接单状态切换触发回调
    changeorderStatus(row) {
      const params = {
        id: row?.id,
        orderStatus: row?.orderStatus === '1'  ? 0 : 1,
      };
      setAccountOrder(params).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.getList();
        }
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.$set(this.queryParams, "pageIndex", 1);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 完全重置到初始状态
      this.$set(this, "queryParams", {
        pageIndex: 1,
        pageSize: 10,
      });
      this.getList();
    },
    // 表格合并处理
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
       // 过滤隐藏项合并父级列,排除操作项
       if (!this.columns.filter(pre=>pre?.visible)[columnIndex].prop.includes('child_')) {
           if (row?.childNum) {
             return {
               rowspan: row?.childNum,// 设置该单元格纵向跨越的行数
               colspan: 1 // 表示不跨列，仅显示在当前列
             };
           } else {
             return {
               rowspan:1,// 不合并默认处理
               colspan: 1 // 不合并默认处理
             };
           }
       } 
    },
    /** 查询列表 */
    getList() {
      // 如果未选择公司给与warning提示
      if(!this.queryParams?.companyId){
        this.$message.warning('请先选择公司')
        return
      }
      this.loading = true;
      queryCrmAccountByPage(this.queryParams).then((response) => {
        // 处理合并数据
        this.dataList = response?.data?.list?.reduce((arr,pre)=>{
          if(pre?.productName?.length){
            // 子项数量
            let childNum = pre?.productName?.length
            arr.push(...pre.productName.map((item,index)=>{
              // 如果为初始项设置子项数量
              if(index === 0){
                  return  {
                    ...pre,
                    ...{
                      child_productName:item
                    },
                    childNum
                  }
              }
              return {
                ...pre,
                ...{
                      child_productName:item
                },
              }
            }
          ))
          }else{
            arr.push(pre)
          }
          return arr
        },[])
        console.log(this.dataList);
        
        this.total = response?.data?.total;
        this.loading = false;
      }).catch((err) => {
        setTimeout(() => {// 延迟2s后自动取消
          this.loading = false;
        }, 2000);
      })
    },
    // 重置属性转化为新对象
    prefixKeys(obj, prefix) {
         return Object.keys(obj).reduce((acc, key) => {
           acc[prefix + key] = obj[key];
           return acc;
         }, {});
    },
    // 修改表格高度触发回调
    updateTableHeight() {
      this.$nextTick(() => {
        this.$refs.table.doLayout();
      });
    },


    // 获取账号详情
    getAccountDetail(row) {
      // 回显表单数据
      this.form = JSON.parse(JSON.stringify(row))
      // 查询一次产品列表
      this.getProductList();
      // 查询一次领导列表
      this.getLeaderList()
    },
    // 处理对话框
    handelDialog(title, row = null) {
      this.title = title + "账号";
      // 回显对象
      this.$set(this,'rowObj',row)
      switch (title) {
        case "添加":
          this.dialogShow = true;
          break;
        case "编辑":
          // 回显数据
          this.getAccountDetail(row);
          this.dialogShow = true;
          break;
        case "密码重置":
          // 回显数据
          resetPassword({id:row?.id}).then(res => { 
            if(res.code == 200){
               this.$message.success("重置成功");
            }
          });
          break;
        default:
        // 其他操作
      }
    },
    /*关闭弹窗*/
    handleClose() {
      this.$refs["formRef"].resetFields();
      this.form = this.$options.data().form;
      this.dialogShow = false;
    },
    // 取消删除
    hanCancelDel() {
      this.$message({
        type: "info",
        message: "已取消删除操作",
      });
    },
    // 删除列表项
    handelDel(row) {
      delAccount(row?.id).then((res) => {
        if (res.code === 200) {
          this.$message.success("删除成功");
          this.getList();
        }
      });
    },
    // 刷新数据且关闭弹框
    handleRefresh() {
      // 刷新数据
      this.getList();
      // 关闭弹窗
      this.handleClose();
    },
    /*提交操作*/
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {};
          params = JSON.parse(JSON.stringify(this.form));
          // 如果是编辑操作咋设置公司id
          if(this.title == "编辑账号"){
            params.companyId = this.queryParams?.companyId
          }
          console.log(params);
            // 添加/编辑操作
            addOrEditCrmAccount(params).then((res) => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.handleRefresh();
              }
            });
            
          }
      });
    },


    // 显示上下线弹出窗回调
    showOrOffPopo(row) {
      // 设置上下线状态
      this.statesUpd = row?.status
      // 设置索引打开弹窗
      this.rowIndex = row?.id
    },
    // 点击取消修改上下线状态
    clickCancelOnOrOff(row){
       this.$message.info("取消操作");
       this.rowIndex = null;
    },
    // 点击提交修改上下线状态
    clickSubmitOnOrOff(row) {
      const params = {
        id: row?.id,
        status:this.statesUpd,
      };
      setAccountStatus(params).then((res) => {
        if(res.code === 200){
          this.$message.success("操作成功");
          this.getList();
          this.rowIndex = null;
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.title {
  font-size: 20px;
  color: #333333;
  font-weight: 500;
}
.search-box {
  margin: 0 0 20px;
  padding: 20px 20px 0;
  background: #fff;
  align-items: flex-start;
  border-radius: 6px;
}
.search-area {
  position: absolute;
  right: 20px;
}
.el-form-item__content {
  flex: 1;
  line-height: 40px;
  position: relative;
  font-size: 14px;
  min-width: 0;
}
::v-deep .el-dialog__body {
  border-top: 1px solid #dfe6ec;
  border-bottom: 1px solid #dfe6ec;
}
.el-table {
  // 滚动条加粗
  --scrollbar-height: 9px;
}
</style>
